<template>
    <div class="use-margin">
        <el-row>
            <el-col :span="12">
                <el-row>
                    <el-input
                        type="textarea"
                        :rows="10"
                        :disabled="showData"
                        placeholder="输入计算公式，例：(\${A} - \${1})/\${2}"
                        v-model="inputValue"
                    >
                    </el-input>
                </el-row>
            </el-col>
            <el-col :span="12" class="use-right">
                <el-row class="uer-operation">
                    <el-button @click="handelAddValue('+', '')" style="background-color:#e6f7ff" :disabled="showData">+</el-button>
                    <el-button @click="handelAddValue('-', '')" style="background-color:#e6f7ff" :disabled="showData">-</el-button>
                    <el-button @click="handelAddValue('*', '')" style="background-color:#e6f7ff" :disabled="showData">*</el-button>
                    <el-button @click="handelAddValue('/', '')" style="background-color:#e6f7ff" :disabled="showData">/</el-button>
                    <el-button @click="handelAddValue('()', '')" style="background-color:#e6f7ff" :disabled="showData">()</el-button>
                </el-row>
                <el-row class="right-add">
                    <p>
                        <span style="color:red;margin-right: 5px;">X</span>控制值
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('X', '控制值')" circle></el-button>
                    </p>
                    <p>
                        <span style="color:red;margin-right: 5px;">A</span>控制值1
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('A', '控制值1')" circle></el-button>
                    </p>
                    <p v-show="showthresholdType2">
                        <span style="color:red;margin-right: 5px;">B</span>控制值2
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('B', '控制值2')" circle></el-button>
                    </p>
                    <p v-show="showthresholdType3">
                        <span style="color:red;margin-right: 5px;">C</span>控制值3
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('C', '控制值3')" circle></el-button>
                    </p>
                    <p>
                        <span style="color:red;margin-right: 5px;">D</span>计算结果
                        <el-button
                            type="primary"
                            icon="el-icon-plus"
                            :disabled="showData"
                            @click="handelAddValue('D', '计算结果')"
                            circle
                        ></el-button>
                    </p>
                    <div v-for="itme in branchDataList" :key="itme.id">
                        <p>
                            <span style="color:red;margin-right: 5px;">{{ itme.id }}</span
                            >{{ itme.name }}
                            <el-button
                                type="primary"
                                icon="el-icon-plus"
                                :disabled="showData"
                                @click="handelAddValue(itme.id, itme.name)"
                                circle
                            ></el-button>
                        </p>
                    </div>
                </el-row>
                <el-row class="right-buts">
                    <el-col :span="4">
                        <el-button type="primary" :disabled="showData" @click="handelAddValue('simulation', '')">案例</el-button>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" :disabled="showData" @click="handelAddValue('verify', '')">校验</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <el-col>
                <el-row>
                    <div class="input-data">
                        {{ inputValueTostring }}
                    </div>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';

@Component({
    name: 'UseMargin',
    components: {
        RiskIconButton,
    },
})
export default class UseMargin extends Vue {
    inputValue: any = '';
    @Prop() branchData!: any[];
    @Prop() entryControl!: any;
    @Prop() riskEntryBranchs!: any;
    @Prop() showData: boolean;
    branchDataList: any[] = [];
    branchAddList: any = {};
    entryControlList: any = {};
    riskEntryBranchsList: any[] = [];
    CountTypeChar = {
        '0': ' + ',
        '1': ' - ',
        '2': ' * ',
        '3': ' / ',
    };
    // eslint-disable-next-line no-template-curly-in-string
    inputValueTostring: any = '${控制值1} - ${分支1})/${分支2}';
    showthresholdType2: boolean = false;
    showthresholdType3: boolean = false;

    // 监听父组件动态传过来的值进行解析
    @Watch('branchData', { immediate: true, deep: true })
    async watchBranchData() {
        let entryBranchCfg = JSON.parse(JSON.stringify(this.branchData));
        this.branchDataList = [];
        for (let i = 0; i < entryBranchCfg.length; i++) {
            if (entryBranchCfg[i].entryBranch.branchType === '0') {
                this.branchDataList.push({ id: String(entryBranchCfg[i].entryBranch.branchNo), name: entryBranchCfg[i].entryBranch.branchName });
            }
        }
    }

    @Watch('entryControl', { immediate: true, deep: true })
    watchusableSubstitute() {
        this.inputValue = this.entryControl.occupySubstitute || '';
        if (this.entryControl.thresholdType2) {
            this.showthresholdType2 = true;
        } else {
            this.showthresholdType2 = false;
        }

        if (this.entryControl.thresholdType3) {
            this.showthresholdType3 = true;
        } else {
            this.showthresholdType3 = false;
        }
    }

    @Watch('riskEntryBranchs', { immediate: true, deep: true })
    watchriskEntryBranchs() {
        this.riskEntryBranchsList = this.riskEntryBranchs;
    }
    // 监听计算公式
    @Watch('inputValue', { immediate: true, deep: true })
    async watchInputValue() {
        let a = [
            {
                id: 'X',
                name: '控制值',
            },
            {
                id: 'A',
                name: '控制值1',
            },
            {
                id: 'B',
                name: '控制值2',
            },
            {
                id: 'C',
                name: '控制值3',
            },
            {
                id: 'D',
                name: '计算结果',
            },
        ];
        let selectDataSource = [];
        selectDataSource.push(...this.branchDataList, ...a);
        let inputValue = this.inputValue;

        if (inputValue) {
            let regex3 = /\$\{(.+?)\}/g;
            let fv = inputValue.match(regex3) || [];
            let cv = inputValue.replace(regex3, '||').split('||') || [];
            let name = [];
            for (let i = 0; i < cv.length; i++) {
                name.push(cv[i]);
                if (fv[i]) {
                    let sn = selectDataSource.find(item => item.id === fv[i].substr(2, fv[i].length - 3)) || {};
                    name.push('${' + sn.name + '}');
                }
            }
            this.inputValueTostring = name.join('');
        } else {
            // eslint-disable-next-line no-template-curly-in-string
            this.inputValueTostring = '${控制值1} - ${分支1})/${分支2}';
        }
        // 回调函数
        this.setBranchData();
    }

    handelAddValue(type: any, val: string) {
        if (['+', '-', '*', '/', '()'].includes(type)) {
            this.inputValue = this.inputValue + type;
        } else if (type === 'simulation') {
            let returnValue = this.createSimulation();
            if (!returnValue) {
                this.yh_message_info('案例生成失败，请手动配置');
            } else {
                this.inputValue = '';
                this.inputValue = returnValue;
            }
        } else if (type === 'verify') {
            this.handleVerify();
            return;
        } else {
            this.inputValue = this.inputValue + '${' + type + '}';
        }
        this.setBranchData();
    }

    // 回调函数
    setBranchData() {
        this.$emit('set-occupy-data', this.inputValue);
    }

    // // 案例
    createSimulation() {
        let entryControl = this.entryControl;
        let entryBranchCfg = this.riskEntryBranchsList || [];
        if (entryBranchCfg.length === 0) {
            return null;
        }
        // 获取最高级别的阀值
        let tt = 'A';
        let maxTT = '0';
        for (let i = 1; i <= 3; i++) {
            if (!entryControl['thresholdType' + i]) {
                continue;
            }
            if (Number(entryControl['thresholdType' + i]) > Number(maxTT)) {
                maxTT = entryControl['thresholdType' + i];
                tt = { '1': 'A', '2': 'B', '3': 'C' }[String(i)];
            }
        }
        // 确认主分支
        let il = entryBranchCfg.filter(item => item.entryBranch.parentBranchNo === 0);
        if (il.length === 2 && il[0].entryBranch.countType !== '3' && il[1].entryBranch.countType === '3') {
            // eslint-disable-next-line
            let returnValue = ' ( ${' + tt + '} - ${D} ) * ';
            if (il[1].entryBranch.branchType === '0') {
                returnValue = returnValue + ' ${' + il[1].entryBranch.branchNo + '}';
            } else {
                returnValue = returnValue + this.findGroupChildren(entryBranchCfg, il[1].entryBranch.branchNo);
            }
            return returnValue;
        } else {
            // eslint-disable-next-line
            return '${' + tt + '} - ${D}';
        }
    }

    findGroupChildren(entryBranchCfg: any, parentBranchNo: any) {
        let formula = '( ';
        let index = 0;
        for (let vaue of entryBranchCfg) {
            if (vaue.entryBranch.parentBranchNo === parentBranchNo) {
                if (index > 0) {
                    formula = formula + this.CountTypeChar[vaue.entryBranch.countType];
                }
                if (vaue.entryBranch.branchType === '0') {
                    formula = formula + '${' + vaue.entryBranch.branchNo + '}';
                } else {
                    formula = formula + this.findGroupChildren(entryBranchCfg, vaue.entryBranch.branchNo);
                }
                index = index + 1;
            }
        }
        formula = formula + ' ) ';
        return formula;
    }

    // 校验
    handleVerify() {
        // let selectDataSource = this.branchDataList;
        let a = [
            {
                id: 'X',
                name: '控制值',
            },
            {
                id: 'A',
                name: '控制值1',
            },
            {
                id: 'B',
                name: '控制值2',
            },
            {
                id: 'C',
                name: '控制值3',
            },
            {
                id: 'D',
                name: '计算结果',
            },
        ];
        let selectDataSource = [];
        selectDataSource.push(...this.branchDataList, ...a);
        let inputValue = this.inputValue || '';
        let regex3 = /\$\{(.+?)\}/g;
        let fv = inputValue.match(regex3) || [];
        let cv = inputValue.replace(regex3, '||').split('||') || [];
        let name = '';
        for (let i = 0; i < cv.length; i++) {
            name += cv[i];
            if (fv[i]) {
                let sn = selectDataSource.find(item => item.id === fv[i].substr(2, fv[i].length - 3)) || {};
                if (sn.name) {
                    name += ' 1 ';
                }
            }
        }
        if (name.length <= 1 || name.trim().length <= 1) {
            this.yh_message_warn('配置公式不正确，请检查');
            return;
        }
        let regp = /[^0-9+\-*/() ]/;
        if (name.match(regp) !== null) {
            this.yh_message_warn('配置公式不正确，请检查');
            return;
        }
        try {
            // eval 并不是仅仅作为解析字符串用。。更多的是执行动态代码上面，例如把字符串作为代码执行
            eval('let result = ' + name); // eslint-disable-line
            this.yh_message_success('配置正确');
        } catch (e) {
            this.yh_message_warn('配置公式不正确，请检查');
        }
    }
}
</script>
<style lang="scss" scoped>
.use-margin {
    color: #222;

    .use-right {
        height: 218px;
        // width: 100%;
        border: 1px solid #eee;

        .uer-operation {
            border-bottom: 1px solid #eee;
            padding: 2px;
        }

        .uer-operation /deep/ .el-button {
            padding: 4px 0px;
        }

        .right-add {
            height: 120px;
            overflow: auto;
            margin-top: 10px;
            padding-left: 5px;
        }

        .right-add /deep/ .el-button.is-circle {
            padding: 2px;
        }

        .right-buts {
            border-top: 1px solid #eee;
            margin-top: 10px;
            padding-top: 10px;
            padding-left: 5px;
        }
    }

    .input-data {
        height: 32px;
        border: 1px solid #eee;
        margin-top: 5px;
        line-height: 32px;
    }
}
</style>
